/**
 * Project Name:dynamicDomain
 * File Name:IPUtil.java
 * Package Name:com.helper.domain.utils
 * Date:2021年4月16日上午9:17:43
 * Copyright (c) 2021, hejiahua@szhuarong.com All Rights Reserved.
 *
*/

package com.helper.domain.utils;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.helper.domain.exception.CustomException;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName:IPUtil <br/>
 * 
 * @author hejiahua
 * @version
 * @see
 */
@Slf4j
public class IPUtil {
	public static String getCookies(String host) throws CustomException {
		try {
			CookieManager manager = new CookieManager();
			manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
			CookieHandler.setDefault(manager);
			URL url = new URL(host);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.getHeaderFields();
			CookieStore store = manager.getCookieStore();
			String cookies = store.getCookies().toString();
			cookies = cookies.replace("[", "");
			cookies = cookies.replace("]", "");
			return cookies;
		} catch (Exception e) {
			log.error("模拟获取cookies失败", e);
			throw new CustomException("模拟获取cookies失败");
		}
	}

	public static boolean validateIP(String ip) {
		String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
		// 判断ip地址是否与正则表达式匹配
		if (ip.matches(regex)) {
			String[] arr = ip.split("\\.");
			for (int i = 0; i < 4; i++) {
				int temp = Integer.parseInt(arr[i]);
				// 如果某个数字不是0到255之间的数 就返回false
				if (temp < 0 || temp > 255)
					return false;
			}
			return true;
		} else
			return false;
	}

	// 查询IP的网站列表
	final static Map<QueryIPType, String[]> ips = new HashMap<>();

	static {
		ips.put(QueryIPType.IPCN, new String[] { "https://www.ipplus360.com/getIP", "https://www.ipplus360.com/getIP" });
		ips.put(QueryIPType.ALIYUN, new String[] { "https://ipinfo.io/ip" });
	}

	public enum QueryIPType {
		IPCN,
		ALIYUN;

		public static QueryIPType getType(String type) {
			for (QueryIPType queryIPType : QueryIPType.values()) {
				if (queryIPType.name().equals(type)) {
					return queryIPType;
				}
			}
			return null;
		}
	}

	public static String getIP(String queryIpType) throws CustomException {
		HttpRequest httpRequest = HttpUtil.createRequest(Method.GET, ips.get(QueryIPType.valueOf(queryIpType))[1]);

		httpRequest.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");

		httpRequest.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

		httpRequest.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

		httpRequest.header("Accept-Encoding", "gzip, deflate");

		httpRequest.header("Referer", "http://127.0.0.1");
		String cookies = getCookies(ips.get(QueryIPType.valueOf(queryIpType))[0]);
		httpRequest.header("Cookie", cookies);
		httpRequest.header("Connection", "keep-alive");
		httpRequest.header("Upgrade-Insecure-Requests", "1");
		httpRequest.cookie(cookies);

		String result = StringUtils.strip(httpRequest.execute().body());
		;
		log.info("IP获取结果：{}", result);
		if (queryIpType.equals(QueryIPType.IPCN.name())) {
			return JSONUtil.parseObj(result).getStr("data");
		} else {
			return result;
		}

	}
}
